from django.shortcuts import render
from django.core.paginator import Paginator
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .ser import *
from utils.comm import send_message
import random

#短信验证码
class SendSms(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        print(mobile)
        code = random.randint(100000, 999999)
        res = send_message(mobile, str(code), 1)
        code = 10010
        if res:
            code = 200
        return Response({"code": code})

#新闻
class Nuws_API(APIView):
    def post(self,request):
        ser = Nuws_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code": 10010})

    def get(self,request):
        id = request.GET.get("id")
        if not id:
            n = Nuws.objects.all()
            cpage = request.GET.get("cpage")
            pag = Paginator(n,2)
            tpage = pag.page(cpage)
            num = pag.num_pages
            ser = Nuws_Ser(tpage,many=True)
            return Response({"code":200,"list":ser.data,'num':num})
        else:
            n = Nuws.objects.filter(id = id).first()
            ser = Nuws_Ser(n)
            return Response({"code":200,"list":ser.data})

#广告
class Advertising_API(APIView):
    def post(self,request):
        ser = Advertising_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code": 10010})

    def get(self,request):
        n = Advertising.objects.all()
        cpage = request.GET.get("cpage")
        pag = Paginator(n, 2)
        tpage = pag.page(cpage)
        num = pag.num_pages
        ser = Advertising_Ser(tpage, many=True)
        return Response({"code": 200, "list": ser.data, 'num': num})

from utils.comm import get_redis_conn
class Test(APIView):
    def get(self,request):
        conn=get_redis_conn()
        conn.setex('username',10,'gxw')
        name=conn.get('username')
        print(name)
        return Response(name)